<?php
/**
 * Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category    Shangku
* @package     Shangku_Freegift
* @copyright   Copyright (c) 2011 Magento Inc. (http://www.magentocommerce.com)
* @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
*/


class Shangku_Freegift_Model_Observer
{
	const SINGLE_GIFT_XML = 'freegift/general/single_gift';
	
	private function _getSingleGiftId()
	{
		return (int)Mage::getStoreConfig(self::SINGLE_GIFT_XML);
	}
	
	public function addSingleGift($observer)
	{
		if (!Mage::helper('freegift')->freeGiftIsActive()){
			return $this;
		}
		
		$productId = $this->_getSingleGiftId();
		if(empty($productId)){
			return $this;
		}
		
		$needAdd = true;
		foreach($this->_getQuote()->getAllItems() as $item){
			if($productId != $item->getData('product_id')){
				continue;
			}
			if($productId == $item->getData('product_id') && $item->getData('gift_type') == Shangku_Freegift_Model_Gift_Type::FREE_GIFT_TYPE_SINGLE){
				$needAdd = false;
				$item->setQty(1);
			}
		}
		
		if ($needAdd){
			$product = Mage::getModel('catalog/product')->load($productId);
			if(!$product->getId()){
				return $this;
			}
			$storeId = Mage::app()->getStore()->getStoreId();
			$item = Mage::getModel('sales/quote_item');
			$item->setProduct($product);
			$item->setQty(1);
			$item->setStoreId($storeId);
			$item->setData('gift_type', Shangku_Freegift_Model_Gift_Type::FREE_GIFT_TYPE_SINGLE);
			$this->_getQuote()->addItem($item);
		}
		
		return $this;
	}
	
	/**
	 * 添加目录规则的礼品
	 * 
	 * @return Shangku_Freegift_Model_Observer
	 */
	public function addGiftProducts($observer)
	{
		if (!Mage::helper('freegift')->freeGiftIsActive()){
			return $this;
		}
		
		$product    = $observer->getEvent()->getProduct();
		$quoteItem    = $this->_getQuote()->getItemByProduct($product);
		
		if (!$quoteItem){
			return $this;
		}
		
		$parentQuoteItemId = $quoteItem->getItemId();
		
		if(!$parentQuoteItemId){
			return $this;
		}
		
		$parentQty = $quoteItem->getQty();

		$giftProductIds = Mage::helper('freegift')->getCategoryGiftsFromProduct($product);
	
		$storeId = Mage::app()->getStore()->getStoreId();
		if (!empty($giftProductIds)){
			foreach($giftProductIds as $productId){
				$product = Mage::getModel('catalog/product')
					->setStoreId($storeId)
					->load($productId);
				$product->setData('price', 0);
				$product->setData('special_price', 0);
				if ($product->getEntityId() != $productId){
					continue;
				}
				$processed = false;
				foreach($this->_getQuote()->getAllItems() as $item){
					if($productId != $item->getData('product_id')){
						continue;
					}
					if($item->getData('gift_type') > 0 && $item->getData('parent_gift_item') == $parentQuoteItemId){
						$processed = true;
						$item->setQty($parentQty);
						$item->save();
					}
				}
				
				if (!$processed){
					$item = Mage::getModel('sales/quote_item');
					$item->setProduct($product);
					$item->setQty($parentQty);
					$item->setStoreId($storeId);
					$item->setData('parent_gift_item', $parentQuoteItemId);
					$item->setData('gift_type', Shangku_Freegift_Model_Gift_Type::FREE_GIFT_TYPE_CATEGORY);
					$item->setData('parent_gift_item', $parentQuoteItemId);
					$item->setQuoteId($this->_getQuote()->getId());
					$item->save();
					
				}
			}
		
		}
		
		return $this;
	}
	private function _getCart()
	{
		return Mage::getSingleton('checkout/cart');
	}
	private function _getQuote()
	{
		return $this->_getCart()->getQuote();
	}
	private function _getSession()
	{
		return Mage::getSingleton('checkout/session');
	}
	/**
	 * 同步礼品,比主产品多的新建一个item或者往同一个不是礼品的item加数量，少的不处理
	 * 购物车规则礼品，默认处理成1，多余的转成普通商品
	 * 
	 * @return Shangku_Freegift_Model_Observer
	 * 
	 */
	public function fixGiftItems($observer)
	{
		if (!Mage::helper('freegift')->freeGiftIsActive()){
			return $this;
		}
		
		$cart = $observer->getEvent()->getCart();
		$storeId = Mage::app()->getStore()->getStoreId();
		
		$needProcessItems = array();
		
		foreach ($cart->getQuote()->getAllItems() as $item) {
			if (!$item) {
				continue;
			}
			if ($item->getData('parent_gift_item') > 0){
				$needProcessItems[$item->getData('parent_gift_item')][] = $item;
			}
			
			if ($item->getData('gift_type') == Shangku_Freegift_Model_Gift_Type::FREE_GIFT_TYPE_CART
					|| 	$item->getData('gift_type') == Shangku_Freegift_Model_Gift_Type::FREE_GIFT_TYPE_SINGLE
				){
				$item->setQty(1);
				//对于购物车类的礼品，因为可能有自定义选项，所以修改数量默认是处理成1个
				/*
				if($newQty > 0){
					$existItem = $this->_getItemByProductId($item->getProductId(), $cart);
					if ($existItem){
						$existItem->setQty($existItem->getQty() + $newQty);
					} else {
						$product = Mage::getModel('catalog/product')->load($item->getProductId());
						$newItem = Mage::getModel('sales/quote_item');
						$newItem->setProduct($product);
						$newItem->setQty($newQty);
						$newItem->setStoreId($storeId);
						$newItem->setData('gift_type', Shangku_Freegift_Model_Gift_Type::FREE_GIFT_TYPE_CART);
						$cart->getQuote()->addItem($newItem);
					}
				}
				*/
			}
		}
		
		foreach($needProcessItems as $parentId => $items){
			foreach($items as $item){
				$parentItem = $cart->getQuote()->getItemById($parentId);
				if (!$parentItem){
					continue;
				}
				$qty = $item->getQty();
				$parentQty = $parentItem->getQty();
				if ($parentQty > 0 && $qty > $parentQty){
					$newQty = $qty - $parentQty;
					$existItem = $this->_getItemByProductId($item->getProductId(), $cart);
					if ($existItem){
						$existItem->setQty($existItem->getQty() + $newQty);
					} else {
						$product = Mage::getModel('catalog/product')->load($item->getProductId());
						$newItem = Mage::getModel('sales/quote_item');
						$newItem->setProduct($product);
						$newItem->setStoreId($storeId);
						$newItem->setQty($newQty);
						$cart->getQuote()->addItem($newItem);
					}
					$item->setQty($parentQty);
				} else {
					$item->setQty($qty);
				}
				$item->setQty($parentItem->getQty());
			}
		}
		
		return $this;
	}
	
	private function _getItemByProductId($productId, $cart)
	{
		foreach ($cart->getQuote()->getAllItems() as $item) {
			if ($item->getProductId() == $productId && !Mage::helper('freegift')->isFreeGiftItem($item)) {
				return $item;
			}
		}
		return false;
	}
	
	public function removeChildGiftItems($observer)
	{
		if (!Mage::helper('freegift')->freeGiftIsActive()){
			return $this;
		}
		
		$parentItem = $observer->getEvent()->getQuoteItem();
		
		if (!$parentItem){
			return $this;
		}
		
		foreach($this->_getQuote()->getAllItems() as $item){
			if ($item->getParentGiftItem() == $parentItem->getItemId()){
				$item->isDeleted(true);
			}
		}
		
		return $this;
	}
	public function fixSingleGift($observer)
	{
		if (!Mage::helper('freegift')->freeGiftIsActive()){
			return $this;
		}
		
		foreach ($observer->getEvent()->getQuote()->getAllItems() as $item) {
			if ($item->getData('gift_type') > 1){//所有购物车类的freegift数量重置为0
				$item->setQty(1);
			}
		}
	}
	
}
